package cbfg.http.util

import cbfg.http.HttpManager
import cbfg.http.constant.PostType
import okhttp3.FormBody
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File

/**
 * @author:  Tom Hawk
 * 添加时间: 2020/9/23 9:59
 * 功能描述:
 */
object PostBodyParser {
    private val MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8")

    fun parse(type: PostType, params: Map<String, Any>): RequestBody {
        return when (type) {
            PostType.FORM -> {
                val builder = FormBody.Builder()
                for ((key, value) in params) {
                    builder.add(key, value.toString())
                }
                builder.build()
            }
            PostType.JSON -> {
                RequestBody.create(
                    MEDIA_TYPE_JSON,
                    HttpManager.gson.toJson(params)
                )
            }
            PostType.MULTI_PART -> {
                //构建请求体
                val builder = MultipartBody.Builder().setType(MultipartBody.FORM)
                //添加请求体
                for ((key, value) in params) {
                    when (value) {
                        is MultipartBody.Part -> builder.addPart(value)
                        is RequestBody -> builder.addFormDataPart(key, null, value)
                        !is File -> builder.addFormDataPart(key, value.toString())
                        else -> {
                            builder.addFormDataPart(
                                key,
                                value.name,
                                RequestBody.create(Utils.getFileMediaType(value.path), value)
                            )
                        }
                    }
                }
                builder.build()
            }
        }
    }
}